package com.example.armmvvm.ui.fallview

import androidx.lifecycle.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancelChildren

/**
 *  author : yanghaozhang
 *  date : 2022/10/19 11:01
 *  description :
 */
abstract class BaseFallView(protected val lifecycleOwner: LifecycleOwner) : IFallView, DefaultLifecycleObserver {

    private val coroutineScopeDelegate = lazy {
        MainScope()
    }

    protected val coroutineScope: CoroutineScope by coroutineScopeDelegate

    private val dismissListener = mutableListOf<BottomFallViewDismissListener>()

    override fun onDestroy(owner: LifecycleOwner) {
        onDismiss()
    }

    /**
     * 弹窗消失hide
     * 注:如果FallView复用,[dismissListener]监听将被清除无效
     */
    override fun onDismiss() {
        lifecycleOwner.lifecycle.removeObserver(this)
        if (coroutineScopeDelegate.isInitialized()) {
            coroutineScope.coroutineContext.cancelChildren()
        }
        dismissListener.forEach {
            it.invoke()
        }
        dismissListener.clear()
    }

    open fun addDismissListener(listener: BottomFallViewDismissListener) {
        dismissListener.add(listener)
    }

    open fun removeDismissListener(listener: BottomFallViewDismissListener) {
        dismissListener.remove(listener)
    }

    open fun clearDismissListener() {
        dismissListener.clear()
    }
}